<template>
  <el-dialog :model-value="visible" @update:model-value="(val) => emit('update:visible', val)" :title="title" center
    @close="handleClose" width="30%">

    <el-form ref="formRef" :model="formData" label-width="100px">
      <!-- 选择指标 - 修改为 TreeSelect 树形选择器 -->
      <el-form-item label="选择指标" prop="indictor_id" :rules="{
        required: true,
        message: '请选择指标',
        trigger: 'change'
      }">
        <el-tree-select v-model="formData.indictor_id" :data="treeOptionsType" :props="treeProps" placeholder="请选择指标"
          @change="handleChange" style="width: 100%" clearable filterable />
      </el-form-item>

      <!-- 选择学期 -->
      <el-form-item label="选择学期" prop="semester_id" :rules="{
        required: true,
        message: '请选择学期',
        trigger: 'change'
      }">
        <el-select v-model="formData.semester_id" placeholder="请选择学期" @change="handleChangeSemester">
          <el-option v-for="item in optionsYear" :key="item.value"
            :label="item.ACADEMICYEAR + '学年&nbsp;&nbsp;' + item.SEMESTER_NAME" :value="item.SEMESTER_ID" />
        </el-select>
      </el-form-item>

      <el-form label-width="100px" ref="listform" :model="listform" >
        <el-form-item :label="value.lable + ':'" :prop="value.lable" :rules="{
          required: value.isrequired == 0 ? true : false,
          message: value.help,
          trigger: 'blur'
        }" v-for="(value, index) in zblist" :key="index">
          <el-input v-if="value.itemtype == 1" v-model="listform[value.lable]" maxlength="400"
            :placeholder="value.help" ></el-input>
          <el-input v-if="value.itemtype == 2" v-model="listform[value.lable]" type="textarea" :rows="4" maxlength="400"
            :placeholder="value.help"></el-input>
          <el-radio v-if="value.itemtype == 3" v-model="listform[value.lable]" :label="ele" @change="changebox"
            v-for="ele in value.dmref" :key="ele">{{ ele }}</el-radio>
          <el-checkbox-group v-model="listform[value.lable]" @change="changebox" v-if="value.itemtype == 4">
            <el-checkbox v-for="ele in value.dmref" :label="ele.text" :key="ele.text"></el-checkbox>
          </el-checkbox-group>
          <el-date-picker v-if="value.itemtype == 5" v-model="listform[value.lable]" type="date" @change="changebox"
            format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" placeholder="选择日期">
          </el-date-picker>
          <el-select v-if="value.itemtype == 6 && value.lable != '奖励级别'" v-model="listform[value.lable]"
            :placeholder="value.help" @change="changebox" style="width: 100%">
            <el-option v-for="ele in value.dmref" :key="ele" :label="ele" :value="ele">
            </el-option>
          </el-select>
          <el-select v-if="value.itemtype == 6 && value.lable == '奖励级别'" v-model="listform[value.lable]"
            @change="changebox" :placeholder="value.help" style="width: 100%">
            <el-option v-for="ele in dictData" :key="ele.TEXT" :label="ele.TEXT" :value="ele.TEXT">
            </el-option>
          </el-select>
          <!-- 数字输入框 -->
          <el-input-number v-if="value.itemtype == 7" class="inputNumber" style="width: 100%" :controls="false" :min="0"
            :max="value.dmref" v-model="listform[value.lable]" :placeholder="value.help" :step="1"
            step-strictly></el-input-number>
        </el-form-item>

        <!-- 证明材料上传 -->
        <el-form-item label="证明材料" prop="files" style="margin-bottom: 0;">
          <el-upload class="upload-demo" :action="uploadUrl" :auto-upload="false" :on-change="handleFileChange"
            :on-remove="handleFileRemove" multiple :file-list="formData.photo" :before-remove="beforeRemove" :limit="5"
            accept=".jpg,.jpeg,.png,.pdf,.doc,.docx">
            <el-button type="primary">上传图片或文档</el-button>
            <template #tip>
              <div class="el-upload__tip text-center">
                支持PNG, JPG, PDF, Word等格式，最大10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

    </el-form>


    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" >保存记录</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
// 1. 首先，导入getCurrentInstance以便能够访问组件实例
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getIndictor } from '@/api/home';
import { addStuRows } from '@/api/list';
import qs from 'qs';
import { useStore } from "@/store";
const store = useStore();
const homeStore = store.home;
const recordStore = store.record;


// 接收的props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '添加新记录'
  }
});


let optionsYear = computed(() => {
  return homeStore.semesterInfo.filter(item => item.SEMESTER_ID == recordStore.semesterid)
})

let optionsType = reactive([]);
// 树形结构数据
let treeOptionsType = ref([]);

// 检测是否为移动设备
const isMobile = ref(false);

const checkDeviceType = () => {
  const width = window.innerWidth;
  isMobile.value = width < 768; // 768px为断点
};


// TreeSelect 配置
const treeProps = {
  value: 'INDICTOR_ID', // 对应值字段
  label: 'NAME',        // 对应标签字段
  children: 'children', // 对应子节点字段
  checkStrictly: true,   // 可以选择任意层级
  emitPath: false
};

// 发出的事件
const emit = defineEmits(['update:visible', 'close', 'save-success']);

const formRef = ref(null);

// 表单数据
const formData = reactive({
  photo: [],        // 证明材料
  // 添加以下两个字段到formData中
  indictor_id: '',  // 指标ID
  semester_id: ''   // 学期ID
});
const fileList = ref([]); // 文件列表
const addup = ref('添加'); // 操作类型，默认为'添加'
let dictData = reactive([])
let zblist = reactive([])
let listform = reactive({ photo: '' })

// 文件上传URL（这里是模拟的，实际需要替换为真实的上传接口）
const uploadUrl = '/api/upload';


// 处理文件变化
const handleFileChange = (file, fileList) => {
  // 这里可以添加文件大小和类型的校验
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('证明材料图片大小不能超过 5MB!')
  }
  if (isLt5M) {
    const reader = new FileReader()
    reader.readAsDataURL(file.raw)
    var obj = {}
    obj.img = file
    obj.fileName = file.name
    reader.onload = () => {
      obj.bas64 = reader.result
    }
    formData.photo.push(obj)
  }
};



// 处理文件移除
const handleFileRemove = (file, fileList) => {
  formData.photo = fileList;
};

// 文件移除前的确认
const beforeRemove = (file) => {
  return ElMessageBox.confirm(`确定要移除 ${file.name} 吗？`);
};

// 关闭模态框
// 1. 修改 handleClose 方法
const handleClose = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 清空listform中的数据，确保类型一致性
  Object.keys(listform).forEach(key => {
    delete listform[key]; // 完全移除属性，而不是设置为空值
  });
  // 保留photo字段并清空
  listform.photo = [];
  emit('update:visible', false);
  emit('close');
};

// 2. 在setup顶部获取当前组件实例
const instance = getCurrentInstance();

// 3. 恢复并修改handleChange函数
const handleChange = async (value) => {
  formData.indictor_id = value;
  await homeStore.getDictCodeData();
  dictData = homeStore.getDictCodeInfo;
  dictData = dictData.filter(item => item.DICTYPE == 'ZD_XT_JLJB');
 

  // 清空zblist但保持响应式
  zblist.splice(0, zblist.length);
  formData.indictor_id = value;
  await homeStore.getPjIndicatorConfigData(value);

  // 获取新数据并排序
  const newData = homeStore.getIndictConfigRowsInfo;
  const sortedData = newData.sort((a, b) => {
    return a.orderno - b.orderno;
  });
  
  // 深拷贝数据并添加到响应式数组
  const deepCopiedData = JSON.parse(JSON.stringify(sortedData));
  zblist.push(...deepCopiedData);

  // 处理引用代码数据
  zblist.forEach(element => {
    if (element.itemtype == 3 || element.itemtype == 4 || element.itemtype == 6) {
      if (element.dmref) {
        let arr = [];
        dictData[element.dmref].forEach(value => {
          arr.push(value.text);
        });
        element.dmref = arr.join(',');
      }
    }
  });
  
  // 关键修改：清空listform，然后使用正确的类型初始化所有字段
  // 1. 首先删除所有现有属性
  Object.keys(listform).forEach(key => {
    delete listform[key];
  });
  // 2. 保留photo字段
  listform.photo = [];
  
  // 3. 根据不同组件类型初始化字段
  zblist.forEach(ele => {
    // 对于文本输入框和下拉选择框，使用空字符串
    if (ele.itemtype === 1 || ele.itemtype === 2 || ele.itemtype === 6) {
      listform[ele.lable] = '';
    }
    // 对于单选框，使用空字符串
    else if (ele.itemtype === 3) {
      listform[ele.lable] = '';
      // 处理选项数据
      if (ele.dmref) {
        ele.dmref = ele.dmref.split(',');
      }
    }
    // 对于多选框，使用空数组
    else if (ele.itemtype === 4) {
      listform[ele.lable] = [];
      // 处理选项数据
      if (ele.dmref) {
        ele.dmref = ele.dmref.split(',').map(a => ({ text: a }));
      }
    }
    // 对于日期选择器，使用null
    else if (ele.itemtype === 5) {
      listform[ele.lable] = null;
    }
    // 对于数字输入框，使用null或数字
    else if (ele.itemtype === 7) {
      ele.dmref = Number(ele.dmref);
      listform[ele.lable] = null;
    }
  });
  
  // 强制组件重新渲染，确保所有输入框正确绑定
  nextTick(() => {
    if (instance && instance.proxy) {
      instance.proxy.$forceUpdate();
    }
  });
};


// 5. 修改保存记录方法
const handleSave = async () => {
  // 深拷贝listform数据
  let listformData = JSON.parse(JSON.stringify(listform));
  
  // 确保formRef存在
  if (formRef.value) {
    formRef.value.validate(async (valid) => {
      if (valid) {
        let submitData = {
          student_id: JSON.parse(sessionStorage.getItem('token')).student_id,
          semester_id: formData.semester_id,
          indictor_id: formData.indictor_id,
          evalrecord: JSON.stringify(listformData),
          photo: JSON.parse(JSON.stringify(formData.photo)),
        };
        
        // 如果是编辑模式，添加record_id
        if (addup.value !== '添加') {
          submitData.record_id = '';
        }
        
        addStuRows(submitData).then(res => {
          if (res.code > 0) {
            ElMessage.success('添加成功');
            handleClose();
          } else {
            ElMessage.error('添加失败');
          }
        });
      }
    });
  }
};


// 选择学期
const handleChangeSemester = (value) => {
  formData.semester_id = value
}

// const handleChange = async (value) => {
//   formData.indictor_id = value
//   await homeStore.getDictCodeData()
//   dictData = homeStore.getDictCodeInfo

//   // 清空zblist但保持响应式
//   zblist.splice(0, zblist.length)
//   formData.indictor_id = value
//   await homeStore.getPjIndicatorConfigData(value)

//   // 获取新数据并排序
//   const newData = homeStore.getIndictConfigRowsInfo
//   const sortedData = newData.sort((a, b) => {
//     return a.orderno - b.orderno
//   })
//   // 深拷贝数据并添加到响应式数组
//   const deepCopiedData = JSON.parse(JSON.stringify(sortedData))
//   zblist.push(...deepCopiedData)

//   // dictData = dictData.filter(item => item.DICTYPE == 'ZD_XT_JLJB')
//   // 处理引用代码数据
//   zblist.forEach(element => {
//     if (
//       element.itemtype == 3 ||
//       element.itemtype == 4 ||
//       element.itemtype == 6
//     ) {
//       if (element.dmref) {
//         let arr = []
//         dictData[element.dmref].forEach(value => {
//           arr.push(value.text)
//         })
//         element.dmref = arr.join(',')
//       }
//     }
//   })
// }

onMounted(async () => {
  await homeStore.getPjIndicatorData();
  await homeStore.getSemesterData();
  optionsYear.value = homeStore.getSemesterInfo;
  optionsType = homeStore.getPjIndicatorInfo;
  // 将扁平数据转换为树形结构
  treeOptionsType.value = convertToTree(optionsType);
});

// 将扁平数据转换为树形结构的函数
function convertToTree(items) {
  // 处理空数据情况
  if (!items || !items.length) return [];

  // 存储所有节点的映射表，键为INDICTOR_ID
  const nodeMap = new Map();
  // 存储所有根节点（PARENT_ID为'0'或空的节点）
  const roots = [];

  // 1. 首先创建所有节点并存储到映射表中
  items.forEach(item => {
    if (item && item.INDICTOR_ID) {
      // 确保每个节点只创建一次
      if (!nodeMap.has(item.INDICTOR_ID)) {
        nodeMap.set(item.INDICTOR_ID, { ...item, children: [] });
      }
    }
  });

  // 2. 重新遍历一次，构建完整的父子关系
  // 这一次我们不依赖于原始数据的遍历顺序，而是直接操作映射表中的节点
  nodeMap.forEach((node, nodeId) => {
    const parentId = node.PARENT_ID || '0';

    // 如果是根节点（PARENT_ID为'0'或找不到父节点）
    if (parentId === '0' || !nodeMap.has(parentId)) {
      // 检查该根节点是否已经在roots数组中，避免重复添加
      if (!roots.some(root => root.INDICTOR_ID === nodeId)) {
        roots.push(node);
      }
    } else {
      // 是子节点，获取父节点并添加到其children数组
      const parentNode = nodeMap.get(parentId);
      // 检查子节点是否已经在父节点的children中，避免重复添加
      if (!parentNode.children.some(child => child.INDICTOR_ID === nodeId)) {
        parentNode.children.push(node);
      }
    }
  });

  // 3. 按ORDERNO排序
  roots.sort((a, b) => (a.ORDERNO || 0) - (b.ORDERNO || 0));

  // 递归对子节点排序
  const sortChildren = (nodes) => {
    if (!nodes || !nodes.length) return;
    nodes.sort((a, b) => (a.ORDERNO || 0) - (b.ORDERNO || 0));
    nodes.forEach(node => sortChildren(node.children));
  };

  sortChildren(roots);
  return roots;
}

</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 20px;
}

.upload-demo {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 0;
  padding: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  cursor: pointer;
  transition: border-color 0.3s;

  &:hover {
    border-color: #409eff;
  }

  .el-button {
    width: auto;
  }

  .el-upload__tip {
    margin-top: 10px;
    color: #909399;
    font-size: 12px;
  }
}

/* 可选：为 TreeSelect 添加一些样式 */
:deep(.el-tree-select) {
  width: 100%;
}
</style>
